package rq.optimize.luban;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Responsible for starting compress and managing active and cached resources.
 */
class Engine {
    private InputStreamProvider srcImg;
    private File tagImg;
    private int srcWidth;
    private int srcHeight;
    private boolean focusAlpha;
    private int maxSize;
    private int mixQuality;
    private int maxInSampleSize;
    private CompressionComputer computer;

    Engine(InputStreamProvider srcImg, File tagImg, boolean focusAlpha, int outFileSize, int mixQuality, int maxInSampleSize,
           CompressionComputer c) throws IOException {
        this.tagImg = tagImg;
        this.srcImg = srcImg;
        this.focusAlpha = focusAlpha;
        this.maxSize = outFileSize;
        this.mixQuality = mixQuality;
        this.maxInSampleSize = maxInSampleSize;
        this.computer = c;


        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inSampleSize = 1;

        BitmapFactory.decodeStream(srcImg.open(), null, options);
        this.srcWidth = options.outWidth;
        this.srcHeight = options.outHeight;
    }


    private int computeSize() {
        srcWidth = srcWidth % 2 == 1 ? srcWidth + 1 : srcWidth;
        srcHeight = srcHeight % 2 == 1 ? srcHeight + 1 : srcHeight;

        int longSide = Math.max(srcWidth, srcHeight);
        int shortSide = Math.min(srcWidth, srcHeight);

        float scale = ((float) shortSide / longSide);
        if (scale <= 1 && scale > 0.5625) {
            if (longSide < 1664) {
                return 1;
            } else if (longSide < 4990) {
                return 2;
            } else if (longSide > 4990 && longSide < 10240) {
                return 4;
            } else {
                return longSide / 1280;
            }
        } else if (scale <= 0.5625 && scale > 0.5) {
            return longSide / 1280 == 0 ? 1 : longSide / 1280;
        } else {
            return (int) Math.ceil(longSide / (1280.0 / scale));
        }
    }

    private Bitmap rotatingImage(Bitmap bitmap, int angle) {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    File compress() throws IOException {
        int kbSize;
        int quality = 90;
        int computeSizeValue = computeSize();
        if (computer != null) {
            computer.setSourceValue(quality, computeSizeValue, srcWidth, srcHeight);
        }
        boolean skip = false;
        int time = 0;
        while (!skip) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            if (computer != null) {
                int res[] = computer.calcQualityAndSampleSize(quality, computeSizeValue);
                if (res == null || res.length == 0) {
                    if (quality > mixQuality) {
                        quality = (int) (quality * 0.95);
                    } else if (computeSizeValue < maxInSampleSize) {
                        computeSizeValue++;
                    }
                } else {
                    quality = res[0];
                    if (res.length > 1) computeSizeValue = res[1];
                }
            } else {
                if (quality > mixQuality) {
                    quality = (int) (quality * 0.95);
                } else if (computeSizeValue < maxInSampleSize) {
                    computeSizeValue++;
                }
            }
            options.inSampleSize = computeSizeValue;
            Bitmap tagBitmap = BitmapFactory.decodeStream(srcImg.open(), null, options);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            if (Checker.SINGLE.isJPG(srcImg.open())) {
                tagBitmap = rotatingImage(tagBitmap, Checker.SINGLE.getOrientation(srcImg.open()));
            }
            tagBitmap.compress(focusAlpha ? Bitmap.CompressFormat.PNG : Bitmap.CompressFormat.JPEG, quality, stream);
            tagBitmap.recycle();

            FileOutputStream fos = new FileOutputStream(tagImg);
            fos.write(stream.toByteArray());
            fos.flush();
            fos.close();
            stream.close();
            kbSize = (int) (FileUtils.getFileSize(tagImg) / 1024);
            int newWidth = srcWidth / computeSizeValue;
            int newHeight = srcHeight / computeSizeValue;
            if (computer != null && computer.isCompressFinish(kbSize, newWidth, newHeight)) {
                skip = true;
            } else if (computer == null) {
                skip = kbSize > maxSize;
            } else {
                skip = ++time > 20;
            }
        }
        return tagImg;
    }
}